﻿using Newtonsoft.Json;
using System;
using System.Text;

namespace eslib.nnp5
{
    /// <summary>
    /// 使用json序列化的数据包
    /// </summary>
    public class JsonSerializedPkg : IPackage
    {
        /// <summary>
        /// 创建新数据包
        /// </summary>
        /// <param name="obj">传递对象</param>
        /// <param name="encode">字符编码</param>
        /// <returns></returns>
        public static JsonSerializedPkg CreateNew(object obj, Encoding encode)
        {
            JsonSerializedPkg spkg = new JsonSerializedPkg();
            spkg.obj = obj;

            string json = JsonConvert.SerializeObject(obj);
            spkg.pkgData = encode.GetBytes(json);

            return spkg;
        }

        /// <summary>
        /// 创建新数据包(使用utf8编码)
        /// </summary>
        /// <param name="obj">传递对象</param>
        /// <returns></returns>
        public static JsonSerializedPkg CreateNew(object obj)
            => CreateNew(obj, Encoding.UTF8);


        /// <summary>
        /// 以缓存转换包，错误时抛出异常
        /// </summary>
        /// <param name="buffer">数据包</param>
        /// <param name="encode">字符编译</param>
        /// <returns></returns>
        public static JsonSerializedPkg Transfer(byte[] buffer, Encoding encode)
        {
            JsonSerializedPkg spkg = new JsonSerializedPkg();
            spkg.pkgData = buffer;
            spkg.obj = JsonConvert.DeserializeObject(encode.GetString(buffer));
            return spkg;
        }

        /// <summary>
        /// 以缓存转换包，错误时抛出异常(使用utf8编码)
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static JsonSerializedPkg Transfer(byte[] buffer)
            => Transfer(buffer, Encoding.UTF8);


        /// <summary>
        /// 包数据
        /// </summary>
        public byte[] pkgData { get; private set; }

        /// <summary>
        /// 包对象
        /// </summary>
        public object obj { get; private set; }



        protected JsonSerializedPkg()
        {
        }



        public byte[] GetBuffer()
        {
            return pkgData;
        }
    }
}
